#include <iostream>
using namespace std;

#include <purewell/barrier.hpp>
#include <purewell/thread.hpp>
#include <purewell/mutex.hpp>
using namespace purewell;

PWMutex* g_pMutex(NULL);

class XThread : public PWThread
{
public:
	virtual void* onStart(void* param)
	{
		PWBarrier& br(*(PWBarrier*)param);
		if ( !br.wait() )
		{
			cerr << this << ": failed to thread barrier!" << endl;
		}
		else
		{
			g_pMutex->lock();
			cerr << this << ": :-D barriered!" << endl;
			g_pMutex->unlock();
		}

		exit(NULL);
	}
};

int
main(int argc, char* argv[])
{
	g_pMutex = PWMutex::create();
	if ( NULL == g_pMutex )
	{
		cerr << "failed to create mutex" << endl;
		return 0;
	}

	void* ret;
	const size_t thrcount(10);
	XThread thr[thrcount];
	PWBarrier* br(PWBarrier::create(thrcount));

	for ( size_t i(0); i<thrcount; i++ )
	{
		cerr << "trying init thr..." << i+1 << endl;
		thr[i].initialize(br);
		sleep(1);
	}

	for ( size_t i(0); i<thrcount; i++ )
	{
		thr[i].wait( &ret );
		thr[i].destroy();
	}

	PWBarrier::release(br);
	PWMutex::release(g_pMutex);
}

